package com.itheima.algorithm.dynamicprogramming;

/**
 * <h3>最长公共字子序列 - 动态规划</h3>
 */
public class LCSubsequence {

    /*
                a   b   c   x   y   z
            0   0   0   0   0   0   0
        a   0   1   1   1   1   1   1
        b   0   1   2   2   2   2   2
        x   0   1   2   2   3   3   4
        y   0   1   2   2   3   4   4
        z   0   1   2   2   3   4   5
     */
    static int lcs(String text1, String text2) {
        int m = text2.length();
        int n = text1.length();
        int[][] dp = new int[m + 1][n + 1];
        for (int i = 1; i < m + 1; i++) {
            for (int j = 1; j < n + 1; j++) {
                if (text1.charAt(j - 1) == text2.charAt(i - 1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Integer.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[m][n];
    }

    public static void main(String[] args) {
        System.out.println(lcs("abcxyz", "abxyz"));
    }
}
